package com.sh.限流算法.漏桶算法;

/**
 * 漏桶算法
 *
 * @author sh
 */
public class LeakyBucketLimiter {
    private long timeStamp = System.currentTimeMillis(); // 上一次水进桶的时间
    private long capacity = 100;   // 桶的容量
    private long rate = 5;  // 每100毫秒放多少
    private long currentWater = 10; // 当前有多少水(请求)

    public LeakyBucketLimiter(long capacity, long rate) {
        this.capacity = capacity;
        this.rate = rate;
    }

    public synchronized boolean limit() {
        long now = System.currentTimeMillis();
        // currentWater - ((now - timeStamp) / 1000) * rate 放水之后的水量
        currentWater = Math.max(0, currentWater - ((now - timeStamp) / 100L) * rate);
//        System.out.println("(now - timeStamp)====>" + (now - timeStamp));
//        System.out.println("(now - timeStamp) / 1000  =====>" + (now - timeStamp) / 100L);
//        System.out.println("放出：" + ((now - timeStamp) / 100L) * rate);
        timeStamp = now;
        if ( (currentWater+1) <capacity ){
            currentWater++;
//            System.out.println("水量" + currentWater);
            return true;
        }else {
            return false;
        }
    }

}
